﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Service;
using MetaQuotes.MT5WebAPI.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RM.Common.DotNetEamil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class AuthenticationVerify : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        private readonly SmtpSettings _emailSender;

        public AuthenticationVerify(mtContext context, IWebHostEnvironment hostingEnv, SmtpSettings emailSender) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
            _emailSender = emailSender;
        }

        #region 列表       
        public IActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="account">姓名/账户ID</param>
        /// <param name="currentReviewer">当前审核人</param>
        /// <param name="createDate">创建时间</param>
        /// <param name="type">信息类型</param>
        /// <param name="state">状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, string account, string currentReviewer, string createDate, string field, string order, int type = -1, int state = -1)
        {

            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmUserInfos
                           join c in _context.CrmUsers on y.CrmId equals c.Id
                           join d in _context.Mt5Users on c.Id equals d.CrmId into dd
                           from dddata in dd.DefaultIfEmpty()
                           select new
                           {
                               index = y.Id,
                               id = y.CrmId,
                               fullName = c.Name,
                               loginName = c.LoginName,
                               informationType = y.Type,
                               state = y.State,
                               createDate = y.CreateDate,
                               currentReviewer = y.Reviewer,
                               endTime = y.OverDate,
                               tradingAccount = dddata.Login.ToString() == null ? 0 : dddata.Login,
                               mt5type = dddata.Type.ToString() == null ? 0 : dddata.Type
                           };
                // data = data.Where(k => k.mt5type == 0);
                //姓/名/账户ID
                if (!string.IsNullOrEmpty(account))
                {
                    long loginNo = 0;
                    try
                    {
                        loginNo = Convert.ToInt64(account);
                    }
                    catch
                    {
                        loginNo = 0;
                    }
                    if (loginNo == 0)
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account));
                    }
                    else
                    {
                        data = data.Where(k => k.loginName.Contains(account) || k.fullName.Contains(account) || k.tradingAccount == loginNo);
                    }
                }
                if (!string.IsNullOrEmpty(currentReviewer))
                {
                    data = data.Where(k => k.currentReviewer.Contains(currentReviewer));
                }
                if (!string.IsNullOrEmpty(createDate) && createDate.Contains(" - "))
                {
                    string[] createDates = createDate.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(createDates[0]);
                    DateTime endTime = Convert.ToDateTime(createDates[1]);
                    data = data.Where(k => k.createDate > startTime && k.createDate < endTime);
                }
                if (type > -1)
                {
                    data = data.Where(k => k.informationType == type);
                }
                if (state > -1)
                {
                    data = data.Where(k => k.state == state);
                }

                if (!string.IsNullOrEmpty(field))
                {
                    if (string.IsNullOrEmpty(order))
                    {
                        data = data.OrderBy(k => field).ThenBy(k => k.index);
                    }
                    else if (order == "asc")
                    {
                        data = data.OrderBy(k => field);
                    }
                    else
                    {
                        data = data.OrderByDescending(k => field);
                    }

                }
                else
                {
                    data = data.OrderBy(k => k.state).ThenByDescending(k => k.createDate);
                }
                res.Count = data.Count();

                res.Data = await data.Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }

        }
        #endregion

        #region 个人信息审核

        public async Task<IActionResult> UserViewDetail(int id)
        {

            int userid = 0;
            #region 个人信息、财务信息、身份信息
            CrmUserInfo userInfo = _context.CrmUserInfos.FirstOrDefault(k => k.Id == id);

            if (userInfo != null)
            {
                ViewBag.userInfos = userInfo;
                userid = userInfo.CrmId;


                //个人信息
                if (!string.IsNullOrEmpty(userInfo.Personal))
                {
                    //List<InputModel> personalInformations = JsonUtil.DeserializeJsonToList<InputModel>(userInfo.Personal);
                    //ViewBag.personalInformations = personalInformations;

                    #region 个人信息                  

                    List<CrmKyc> personalInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(userInfo.Personal);
                    ViewBag.personalType = userInfo.State;
                    ViewBag.personalInformations = personalInformations;
                    #endregion
                }
                else
                {
                    ViewBag.personalInformations = null;
                }
                //财务信息
                if (!string.IsNullOrEmpty(userInfo.Financial))
                {
                    List<CrmKyc> financialInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(userInfo.Financial);
                    ViewBag.financialInformations = financialInformations;
                }
                else
                {
                    ViewBag.financialInformations = null;
                }
                //身份信息
                if (!string.IsNullOrEmpty(userInfo.Identity))
                {
                    List<InputModel> identityInformation = JsonUtil.DeserializeJsonToList<InputModel>(userInfo.Identity);
                    ViewBag.identityInformation = identityInformation;
                }
                else
                {
                    ViewBag.identityInformation = null;
                }
            }
            #endregion

            #region 账户信息
            CrmUser crmUser = await _context.CrmUsers.FindAsync(userid);
            if (crmUser == null)
            {
                return NotFound();
            }
            #endregion

            #region 审核记录

            var data = from y in _context.CrmAuditLogs
                       join c in _context.TbUsers on y.ReviewerId equals c.Id into cc
                       from ccdata in cc.DefaultIfEmpty()
                       join d in _context.CrmUsers on y.CrmId equals d.Id
                       select new CrmAuditLog
                       {
                           Id = y.Id,
                           OrderId = y.OrderId,
                           CrmId = y.CrmId,
                           Type = y.Type,
                           Cont = y.Cont,
                           Remark = y.Remark,
                           Reviewer = y.ReviewerId != null ? ccdata.UserName : d.Name,
                           CreateDate = y.CreateDate,
                           ReviewerId = y.ReviewerId

                       };
            var crmAuditLogs = data.Where(k => k.OrderId == userInfo.Id.ToString() && k.Type == userInfo.Type).OrderBy(p => p.Id).ToList();
            ViewBag.crmAuditLogsList = crmAuditLogs;
            #endregion

            #region 登录用户名
            ViewBag.LoginName = User.UserName;
            #endregion

            return View(crmUser);
        }
        #endregion

        #region 保存审核信息
        [HttpPost]
        public async Task<JsonResult> Edit(int Id, int State, string Remarks, string Reviewer)
        {
            Result res = new Result();
            try
            {
                if (State == 0)
                {
                    res.Code = 1;
                    res.Msg = "incompleteInformation";
                    return new JsonResult(res);
                }
                #region 使用默认的服务器
                Mt5Server mt5Server = _context.Mt5Servers.Where(k => k.State == 1 && k.Type == 1).OrderByDescending(k => k.Default).ThenBy(k => k.Sort).FirstOrDefault();
                if (mt5Server == null)
                {
                    res.Code = 1;
                    res.Msg = "warningMt5";
                    return new JsonResult(res);
                }

                #endregion

                #region 当审核个人信息的时候需要新增MT5账号
                CrmUserInfo model = await _context.CrmUserInfos.FindAsync(Id);
                CrmUser crmUser = await _context.CrmUsers.FindAsync(model.CrmId);
                Mt5User mt5User = _context.Mt5Users.Where(k => k.CrmId == crmUser.Id).FirstOrDefault();
                if (crmUser == null)
                {
                    res.Code = 1;
                    res.Msg = "getUserDetailsFail";
                    return new JsonResult(res);
                }
                else
                {
                    #region 判断状态是否改变
                    if (model.State != 0)
                    {
                        res.Code = 1;
                        res.Msg = "warningUser";
                        return new JsonResult(res);
                    }
                    #endregion

                    if (State == 2 && model.Type == 1 && mt5User == null)
                    {

                        #region 注册MT5账号信息
                        MT5CommonHelper mT5CommonHelper = new MT5CommonHelper();
                        string pwd = CommonHelper.pass(8, "!@#$");
                        MTUser mu = new MTUser();
                        MTUser outmu = new MTUser();
                        MTUser outmu1 = new MTUser();
                        //mu.Login = 286095;                      
                        List<CrmKyc> personalInformations = JsonUtil.DeserializeJsonToList<CrmKyc>(model.Personal);
                        CrmKyc inputModel = personalInformations.Where(k => k.Name == "name").FirstOrDefault();
                        if (inputModel != null)
                        {
                            mu.Name = inputModel.Value;
                        }
                        else
                        {
                            mu.Name = crmUser.LoginName;
                        }
                        //mu.Name = crmUser.Name;
                        mu.MainPassword = pwd;
                        mu.InvestPassword = pwd;
                        mu.Phone = crmUser.Telephone;
                        mu.Email = crmUser.Email;
                        mu.Group = "preliminaryAff";
                        mu.Leverage = 100;//用户杠杆的大小
                                          //允许用户连接、允许用户更改密码、允许用户使用追踪止损、允许用户接收每日报告
                        mu.Rights = (MTUser.EnUsersRights.USER_RIGHT_ENABLED | MTUser.EnUsersRights.USER_RIGHT_PASSWORD | MTUser.EnUsersRights.USER_RIGHT_TRAILING | MTUser.EnUsersRights.USER_RIGHT_REPORTS);
                        bool MTRetCode = mT5CommonHelper.Registered(_context, mu, out outmu);
                        string server = mt5Server.MetatraderServer + ":" + mt5Server.MetatraderPort;
                        await NetEmailClient.SendMailByConfig(crmUser.Email, "MT5账号注册", NetEmailClient.Getsuccessful(crmUser.LoginName, outmu.Login.ToString(), pwd, server), "");

                        #endregion

                        if (MTRetCode == false)
                        {
                            res.Code = 1;
                            res.Msg = "failedToRegisterMT5Account";
                            return new JsonResult(res);
                        }
                        else
                        {
                            #region 新增MT5真实用户表
                            mt5User = new Mt5User();
                            mt5User.Login = Convert.ToInt64(outmu.Login);
                            mt5User.Type = 0;
                            mt5User.Server = server;
                            mt5User.CrmId = crmUser.Id;
                            mt5User.Group = "preliminaryAff";
                            //mt5User.Firstname = crmUser.Firstname;
                            //mt5User.Lastname = crmUser.Lastname;
                            mt5User.Company = outmu.Company;
                            mt5User.Country = outmu.Country;
                            mt5User.Language = (int)outmu.Language;
                            mt5User.City = outmu.City;
                            mt5User.State = outmu.State;
                            mt5User.Zipcode = outmu.ZIPCode;
                            mt5User.Address = outmu.Address;
                            mt5User.Phone = outmu.Phone;
                            mt5User.Email = outmu.Email;
                            mt5User.Laverage = (int)outmu.Leverage;
                            mt5User.Creator = User.UserName;
                            mt5User.CreateDate = DateTimeUtil.Now;
                            mt5User.Balance = 0;
                            mt5User.Equity = 0;
                            mt5User.Floating = 0;
                            mt5User.Margin = 0;
                            mt5User.MarginFree = 0;
                            mt5User.MarginLevel = 0;
                            mt5User.Profit = 0;
                            mt5User.Storage = 0;
                            _context.Add(mt5User);

                            #endregion

                            #region 新增MT5模拟用户表
                            //mt5User = new Mt5User();
                            //mt5User.Login = Convert.ToInt64(outmu1.Login);
                            //mt5User.Type = 1;
                            //mt5User.Server = "";
                            //mt5User.CrmId = crmUser.Id;
                            //mt5User.Group = "demo\\demoforex";
                            //mt5User.Firstname = crmUser.Firstname;
                            //mt5User.Lastname = crmUser.Lastname;
                            //mt5User.Company = outmu1.Company;
                            //mt5User.Country = outmu1.Country;
                            //mt5User.Language = outmu1.Language.ToString();
                            //mt5User.City = outmu1.City;
                            //mt5User.State = outmu1.State;
                            //mt5User.Zipcode = outmu1.ZIPCode;
                            //mt5User.Address = outmu1.Address;
                            //mt5User.Phone = outmu1.Phone;
                            //mt5User.Email = outmu1.Email;
                            //mt5User.Laverage = outmu1.Leverage.ToString();
                            //mt5User.Creator = User.UserName;
                            //mt5User.CreateDate = DateTimeUtil.Now;
                            //_context.Add(mt5User);
                            #endregion

                            #region 修改CRM个人信息审核表
                            model.State = State;
                            model.Remarks = Remarks;
                            model.Reviewer = Reviewer;
                            model.OverDate = DateTimeUtil.Now;
                            #endregion                           

                            #region 新增审核记录
                            CrmAuditLog crmAuditLog = new CrmAuditLog();
                            crmAuditLog.OrderId = model.Id.ToString();
                            crmAuditLog.CrmId = model.CrmId;
                            crmAuditLog.Type = model.Type;
                            if (State == 2)
                                crmAuditLog.Cont = "审核通过";
                            else
                                crmAuditLog.Cont = "审核拒绝";
                            crmAuditLog.Reviewer = User.UserName;
                            crmAuditLog.Remark = Remarks;
                            crmAuditLog.CreateDate = DateTimeUtil.Now;
                            crmAuditLog.ReviewerId = User.Id;
                            _context.Add(crmAuditLog);
                            #endregion


                            #region 更新CRM姓名
                            crmUser.Name = mu.Name;
                            #endregion

                            res.Code = 0;
                            res.Data = await _context.SaveChangesAsync();
                            return new JsonResult(res);
                        }
                    }
                    else
                    {
                        #region 修改CRM财务信息、身份信息审核表
                        model.State = State;
                        model.Remarks = Remarks;
                        model.Reviewer = Reviewer;
                        model.OverDate = DateTimeUtil.Now;
                        #endregion

                        #region 回更用户表idNo身份证信息           
                        //if (!string.IsNullOrEmpty(model.Identity))
                        //{
                        //    List<CrmKyc> temlist = JsonUtil.DeserializeJsonToList<CrmKyc>(model.Identity);
                        //    foreach (CrmKyc inputModel in temlist)
                        //    {
                        //        if (inputModel.Name == "idNo")
                        //            crmUser.IdNo = inputModel.Value;
                        //    }
                        //}

                        #endregion

                        #region 新增审核记录
                        CrmAuditLog crmAuditLog = new CrmAuditLog();
                        crmAuditLog.OrderId = model.Id.ToString();
                        crmAuditLog.CrmId = model.CrmId;
                        crmAuditLog.Type = model.Type;
                        if (State == 2)
                            crmAuditLog.Cont = "审核通过";
                        else
                        {
                            crmAuditLog.Cont = "审核拒绝";
                            #region 发送审核失败邮件
                            await NetEmailClient.SendMailByConfig(crmUser.Email, "信息审核失败", NetEmailClient.AuditFailed(), "");
                            #endregion
                        }

                        crmAuditLog.Reviewer = User.UserName;
                        crmAuditLog.ReviewerId = User.Id;
                        crmAuditLog.Remark = Remarks;
                        crmAuditLog.CreateDate = DateTimeUtil.Now;
                        _context.Add(crmAuditLog);
                        #endregion



                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                        return new JsonResult(res);
                    }
                }
                #endregion


            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);

            }

        }
        #endregion
    }
}
